package com.example.inventoryservice.controller;

import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.pattern.Patterns;
import akka.util.Timeout;
import com.example.inventoryservice.actor.PersistentInventoryActor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletionStage;

/**
 * 库存控制器
 * 提供REST API接口，通过Akka Actor管理库存
 */
@Slf4j
@RestController
@RequestMapping("/api/inventory")
public class InventoryController {

    @Autowired
    private ActorSystem actorSystem;

    private final Timeout timeout = Timeout.create(Duration.ofSeconds(5));

    /**
     * 获取库存状态
     */
    @GetMapping("/status")
    public ResponseEntity<String> getInventoryStatus() {
        try {
            log.info("获取库存状态请求");
            
            ActorRef inventoryActor = actorSystem.actorOf(PersistentInventoryActor.props(), "inventory-manager");
            
            PersistentInventoryActor.GetInventoryStatus getStatusCmd = new PersistentInventoryActor.GetInventoryStatus();
            
            CompletionStage<Object> future = Patterns.ask(inventoryActor, getStatusCmd, timeout);
            
            return future.thenApply(response -> {
                PersistentInventoryActor.InventoryStatus result = (PersistentInventoryActor.InventoryStatus) response;
                Map<String, Object> status = result.getStatus();
                
                if (status == null) {
                    return ResponseEntity.internalServerError().body("获取库存状态失败");
                }
                
                return ResponseEntity.ok("库存状态: " + status.toString());
            }).toCompletableFuture().get();
            
        } catch (Exception e) {
            log.error("获取库存状态异常: {}", e.getMessage(), e);
            return ResponseEntity.internalServerError().body("获取库存状态异常: " + e.getMessage());
        }
    }

    /**
     * 初始化库存
     */
    @PostMapping("/initialize")
    public ResponseEntity<String> initializeInventory(@RequestBody InitializeInventoryRequest request) {
        try {
            log.info("初始化库存请求: {}", request);
            
            ActorRef inventoryActor = actorSystem.actorOf(PersistentInventoryActor.props(), "inventory-manager");
            
            PersistentInventoryActor.InitializeInventory initCmd = new PersistentInventoryActor.InitializeInventory(
                request.getInitialInventory()
            );
            
            CompletionStage<Object> future = Patterns.ask(inventoryActor, initCmd, timeout);
            
            return future.thenApply(response -> {
                PersistentInventoryActor.InventoryInitialized result = (PersistentInventoryActor.InventoryInitialized) response;
                if ("SUCCESS".equals(result.getStatus())) {
                    return ResponseEntity.ok("库存初始化成功");
                } else {
                    return ResponseEntity.badRequest().body("库存初始化失败");
                }
            }).toCompletableFuture().get();
            
        } catch (Exception e) {
            log.error("初始化库存异常: {}", e.getMessage(), e);
            return ResponseEntity.internalServerError().body("初始化库存异常: " + e.getMessage());
        }
    }

    // 请求DTO类
    public static class InitializeInventoryRequest {
        private Map<String, Integer> initialInventory;

        public InitializeInventoryRequest() {}

        public InitializeInventoryRequest(Map<String, Integer> initialInventory) {
            this.initialInventory = initialInventory;
        }

        public Map<String, Integer> getInitialInventory() { return initialInventory; }
        public void setInitialInventory(Map<String, Integer> initialInventory) { this.initialInventory = initialInventory; }
    }
}
